const state = {
    examId: "",
    time: null,
    startTime: "",
    list: [{}],
    activeIdx: 0,
    answerList: [{}],
    examInfo: {},
};

const mutations = {
    SET_examId: (state, examId) => {
        state.examId = examId;
    },
    SET_startTime: (state, time) => {
        state.startTime = time;
    },
    SET_time: (state, time) => {
        state.time = time;
    },
    SET_activeIdx: (state, activeIdx) => {
        state.activeIdx = activeIdx;
    },
    SET_list: (state, list) => {
        state.list = JSON.parse(JSON.stringify(list));
    },
    SET_answerList: (state, answerList) => {
        state.answerList = JSON.parse(JSON.stringify(answerList));
    },
    SET_examInfo: (state, examInfo) => {
        state.examInfo = JSON.parse(JSON.stringify(examInfo));
    },
    CLEAR_EXAM: state => {
        state.examId = "";
        state.time = null;
        state.startTime = "";
        state.activeIdx = 0;
        state.list = [{}];
        state.answerList = [{}];
        state.examInfo = {};
    },
};

const actions = {
    // user login
    login({ commit }, userInfo) {
        const { username, password, identityEnum } = userInfo;
        return new Promise((resolve, reject) => {
            APIs.login({ username: username.trim(), password: password, identityEnum })
                .then(response => {
                    console.log(response);
                    commit("SET_USERINFO", response);
                    resolve();
                })
                .catch(error => {
                    reject(error);
                });
        });
    },

    // user logout
    logout({ commit, state }) {
        return new Promise((resolve, reject) => {
            APIs.logout({ params: { token: state.token } })
                .then(() => {
                    commit("SET_TOKEN", "");
                    removeToken();
                    resolve();
                })
                .catch(error => {
                    reject(error);
                });
        });
    },

    // remove token
    resetToken({ commit }) {
        return new Promise(resolve => {
            commit("SET_TOKEN", "");
            removeToken();
            resolve();
        });
    },
};

export default {
    namespaced: true,
    state,
    mutations,
    actions,
};
